<template>
	<page-meta :page-style="'overflow:'+(uniPopupShow ? 'hidden':'visible')"></page-meta>
	<view class="detail-page">
		<!-- 导航栏 -->
		<!-- #ifndef MP-WEIXIN -->
		<free-nav-bar textContent="" :isBackShow="true" style="z-index: 1000;"></free-nav-bar>
		<!-- #endif -->
		<view class="spu-detail" id="head" :style="{height: scrollerHeight + 'px'}">
			<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltoupper="upper"
				@scrolltolower="lower" @scroll="scroll" :style="{height: scrollerHeight + 'px'}">
				<view class="detail-top">
					<view class="spu-banner">
						<view class="uni-margin-wrap">
							<swiper class="swiper" circular :indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval"
								:duration="duration">
								<swiper-item v-for="(img, index) in product.sliderPicUrls" :key="img">
									<!-- <view class="swiper-item uni-bg-red">A</view> -->
									<image style="width: 100%; height: 100%;" :src="img"></image>
								</swiper-item>
								<!-- <swiper-item>
									<view class="swiper-item uni-bg-green">B</view>
								</swiper-item>
								<swiper-item>
									<view class="swiper-item uni-bg-blue">C</view>
								</swiper-item> -->
							</swiper>
						</view>
					</view>
					<view class="spu-title">
						<view class="spu-price">
							<h2 style="color: #FD5052;"> <span>￥</span> {{parseToYuan(chooseSku.price)}}</h2>
							<view class="sale_price" v-if="chooseSku.salePrice > 0">￥{{parseToYuan(chooseSku.salePrice)}}</view>
						</view>
						<view class="spu-title-info">
							<view class="spu-name">
								{{product.name}}
							</view>
							<view class="share">								
								<button class="leftBox" open-type="share" style="width: 60px;border: none;background-color: #fff;">
									<span class="share-icon" style="margin-top: 10rpx;margin-bottom: 0px;"><img src="@/static/images/share.svg" alt=""></span>
									<span class="share-text">分享</span>
								</button>
							</view>
						</view>
						
						<view class="spu-desc">
							<p class="subinfo">{{product.introduction}}</p>
						</view>					
					</view>
					<view class="sku-box">
						<uni-list>
							<uni-list-item title="产地" clickable>								
								<!-- 自定义 header -->
								<template v-slot:header>
									<view class="slot-box">产地</view>
								</template>
								<!-- 自定义 body -->
								<template v-slot:body>
									<text class="slot-box slot-text" style="color: #666666;">{{product.producingArea}}</text>
								</template>							
							</uni-list-item>
							<uni-list-item title="选择" :clickable="true"   @click="chooseSkuHandle" showArrow>
								<template v-slot:header>
									<view class="slot-box">选择</view>
								</template>
								<!-- 自定义 body -->
								<template v-slot:body>
									<text class="slot-box slot-text" style="color: #666666;">{{currentSkuName}}</text>
								</template>	
								<!-- <template v-slot:footer>
									<icon></icon>
								</template> -->
							</uni-list-item>
							<uni-list-item title="" :clickable="true"  @click="changeAddress" showArrow>
								<template v-slot:header>
									<view class="slot-box" style="min-width: 70rpx;">送至</view>
								</template>
								<!-- 自定义 body -->
								<template v-slot:body>
									<text style="color: #666666;font-size: 14px;white-space: nowrap;" v-if="userDefaultAddr && userDefaultAddr !=''" 
										class="slot-box slot-text">{{userDefaultAddr}}</text>
								</template>	
							</uni-list-item>
						</uni-list>			
					</view>
				</view>
				<view class="spu-info">
					<uni-section title="商品详情"></uni-section>
					<view class="info-detail">
						<!-- <view class="spu-images" v-html="product.description"></view> -->
						<rich-text class="spu-images" 
						:nodes="formatRichText(product.description)" 
						:selectable="false"></rich-text>
					</view>
				</view>
			</scroll-view>		
		</view>
		
		<!-- SKU 选择框 -->
		<uni-popup ref="skuPopup" type="bottom" borderRadius="10px 10px 0 0" background-color="#fff" @change="skuPopupChange">
			<view style="position: relative;float: right;z-index: 20;right: 20rpx;top: 20rpx;" @click="closeSkuPopup">
				<uni-icons type="closeempty" size="24"></uni-icons> 
			</view>
			<view class="sku-choose-block">
				<view class="sku-choose-box">
					<uni-section class="sku-info" title="" padding>
						<view class="sku-icon">
							<image style="width: 150rpx; height: 150rpx;" :src="chooseSku.icon ? chooseSku.icon : product.picUrl"/>
						</view>						
						<view class="choose-sku">
							<view class="sku-price">
								<h2 style="color: #FD5052;"> <span>￥</span> {{parseToYuan(chooseSku.price)}}</h2>
							</view>
							<view class="sku-name" style="color: #666666;">
								已选规格：{{chooseSku.name}}
							</view>
						</view>					
					</uni-section>
					<uni-section class="sku-list" :clickable="true" title="规格选择" padding>
						<view class="sku-list-item" v-for="(sk,index) in skuList" :key="index">
							<uni-tag :inverted="true" :text="sk.skuName" class-prefix="my-tag" v-if="sk.selected" custom-style="border-color: #FD5052" 
							@click="selectSku(sk)"/>
							<uni-tag :inverted="true" :text="sk.skuName" v-else custom-style="border-color: #666666"
							@click="selectSku(sk)"/>
						</view>					
					</uni-section>
					<uni-section class="sku-buy-num" :clickable="true" title="数 量" padding>
						 <template v-slot:right>
						   <uni-number-box :min="1" v-model="chooseSku.buyNum" @change="changeBuyNum" />
						  </template>						
					</uni-section>
					<uni-section class="sku-buy-num" title="保 障" titleColor="#FD5052" padding>
						 <template v-slot:right>
						   <uni-tag :inverted="true" text="坏果包换" type="error" />
						  </template>						
					</uni-section>
				</view>	
				<view class="sku-choose-btn">
					<button class="choose-btn" @click="chooseBuy">{{cartBtnLabel}}</button>
				</view>	
			</view>
		</uni-popup>
		
		<view class="detail-bottom">
			<view class="detail-bottom__left">
				<view class="news flex">
					
						<span class="icon">
							<image src="http://oss.town168.com/oss/web/icon/news.png" style="width: 100%;height: 100%;" alt="" />
							<!-- <span class="info-num"></span> -->
						</span>
						<button class="leftBox" type="default" plain="true" style="border: none;height: 36rpx;line-height: 36rpx;margin-top: 6rpx;background-color: #fff;" open-type="im"
						  data-im-id="dy51ywke7l92">
							<span class="title">联系客服</span>		
						</button>
				</view>	
				<view class="cart flex" @click="goCartList">
					<span class="icon">
						<image src="http://oss.town168.com/oss/web/icon/cart.png"  style="width: 100%;height: 100%;" alt="" />
						<span class="info-num" v-if="cartTotal && cartTotal > 0">{{cartTotal}}</span>
					</span>
					<span class="title" style="margin-top: 6rpx;">购物车</span>
				</view>
			</view>
			<view class="detail-bottom__right">
				<view class="flex placeorder" @click="goBuyNow">
					立即下单
				</view>
				<view class="flex addtocart" @click="addToCartHandle">
					加入购物车
				</view>	
			</view>
		</view>
		<!-- 选择收货地址 -->
		<uni-popup ref="addressPopup" @change="addressPopupChange" type="bottom" borderRadius="10px 10px 0 0" background-color="#fff" style="height: 360rpx;max-height: 460rpx;">
			
			<address-list-item :list-data="myAddrList" :show-wei-xin-addr="true"
				@close-addres-list="closeAddresList"
				@select-address="selectAddress" :show-title="true"></address-list-item>
			
		</uni-popup>
	</view>
</template>

<script>
	import freeNavBar from "@/components/free-ui/free-nav-bar.vue"
	import addressListItem from "@/components/free-ui/address-list-item.vue"
	import $U from '@/common/free-lib/util.js';
	import $H from '@/common/free-lib/request.js';
	import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue'
	export default {
		components: {
			freeNavBar,
			addressListItem,
			uniPopup
		},
		data() {
			return {
				phoneHeight: 0, //屏幕可用高度
				topHeight: 0, //滑块上方高度
				bottomHeight: 0, //底部高度
				scrollerHeight:0,
				scrollTop: 0,
				cartBtnLabel: '加入购物车',
				old: {
					scrollTop: 0
				},
				indicatorDots: true,
				autoplay: true,
				interval: 2000,
				duration: 500,
				product: {},
				productSkus: [],
				currentPrice: 0.1,
				userDefaultAddr: '',
				currentSkuName: '请选择规格',
				skuList: [],
				isDirect: false,
				chooseSku: {
					productId: undefined,
					skuId: undefined,
					icon: '',
					name: '',
					buyNum: 1,
					price: 0,
					salePrice: 0
				},
				cartTotal: 0,
				formData: {
					productId: undefined,
					skuId: undefined,
					num:1
				},
				myAddrList: [],
				currentAddress: {},
				uniPopupShow:false
			}
		},
		onLoad(e){
			if(e && e.pid) {
				this.getSpuHandle(e.pid);
			}
			// this.getSpuHandle(633);
			this.getCartItemNum();
			this.getDefaultAddress();
		},
		onShow() {
			this.getMyAddressList();
		},
		onReady() {
			var height = 0;
			var _this = this;
			uni.getSystemInfo({
				success: function(res) {
					_this.phoneHeight = res.windowHeight;					
					_this.$nextTick(() => {
						let view = uni.createSelectorQuery().select("#head"); //局部滑块
						view.boundingClientRect(data => {
							_this.topHeight = data.height;
							height = _this.phoneHeight - _this.topHeight - 44;							
							_this.scrollerHeight = height;
						}).exec();
					})
				},
			}); 
		},
		methods: {			
			formatRichText(html) { // 富文本内容格式化
				return html && html.replace(/<img[^>]*>/gi, function(match, capture) { // 查找所有的 img 元素
					return match.replace(/style=".*"/gi, '').replace(/style='.*'/gi, ''); // 删除找到的所有 img 元素中的 style 属性
				}).replace(/\<img/gi, '<img style="width:100%;"'); // 对 img 元素增加 style 属性，并设置宽度为 100%
			},
			contact() {
				
			},
			getSpuHandle(pid) {
				if(pid && pid > 0) {
					let _this = this
					$H.get('/product/spu/getDetail', {id: pid}).then(res => {
						if(res) {							
							_this.product = res;
							_this.skuList = res.skus;
							_this.chooseSku.productId = res.id;
							_this.skuHandle();
						}
					})
				}
			},
			changeBuyNum() {},
			changeAddress(){
				this.getMyAddressList();
				this.$refs.addressPopup.open('bottom')
			},
			closeAddresList() {
				this.$refs.addressPopup.close()
			},
			selectAddress(e){
				this.currentAddress = e;
				this.userDefaultAddr = e.detailAddress;
				this.$refs.addressPopup.close();
			},
			getMyAddressList() {
				  let _this = this;
				  if($U.isLogin()) {
					  $H.get('/member/address/list').then(res => {
						 if(res) {
							_this.myAddrList = res;						
						 }
					  })
				  }				  
			},
			skuHandle() {
				let _this = this
				let newSkuList = [];
				if(this.skuList && this.skuList.length > 0) {
					this.skuList.forEach((item, index) => {
						if(item.properties && item.stock && item.stock > 0) {
							let name = ''
							item.properties.forEach((p,i) => {
								name += p.valueName;
								if(i < (item.properties.length - 1) ) {
									name += '、';
								}
							})
							item.skuName = name;		
							if(index == 0) {
								item.selected = true;
								_this.chooseSku.icon = item.picUrl
							}
							else {
								item.selected = false;
							}
							newSkuList.push(item);
						}
					})
					// this.selectSku(this.skuList[0])
					this.skuList = newSkuList
					this.skuList[0].selected = true;
					let sku = this.skuList[0];
					console.log(sku)
					this.chooseSku = {
						productId: this.product.id,
						skuId: sku.id,
						icon: sku.picUrl,
						name: sku.skuName,
						buyNum: 1,
						price: sku.price,
						salePrice: sku.marketPrice
					}
				}				
			},
			parseToYuan(price) {
				return $U.fenToYuan(price);
			},
			chooseSkuHandle() {
				this.cartBtnLabel = '加入购物车';
				this.$refs.skuPopup.open('bottom');
				
			},
			closeSkuPopup() {
				this.$refs.skuPopup.close()
			},
			skuPopupChange(e) {
				this.uniPopupShow = e.show;
			},
			addressPopupChange(e) {
				this.uniPopupShow = e.show;
			},
			addToCartHandle() {
				this.isDirect = false;
				if($U.isLogin()) {
					this.cartBtnLabel = '加入购物车';
					this.selectSku(this.skuList[0]);
					this.$refs.skuPopup.open('bottom')
				}
				else {
					uni.navigateTo({url: '/pages/common/login/login?from=' + 'notTab'})
				}
			},
			selectSku(sku) {
				this.skuList.forEach((item, i) => {
					item.selected = false;
				});	
				sku.selected = true;
				this.currentSkuName = sku.skuName;
				this.chooseSku.skuId = sku.id;
				this.chooseSku.name = sku.skuName;
				this.chooseSku.price = sku.price;
				this.chooseSku.salePrice = sku.marketPrice
			},
			chooseBuy() {
				this.currentSkuName = this.chooseSku.name;
				if($U.isLogin()) {
					this.formData = {
						productId: this.chooseSku.productId,
						skuId: this.chooseSku.skuId,
						num: this.chooseSku.buyNum
					}
					
					let data = {
						skuId: this.chooseSku.skuId,
						count:this.chooseSku.buyNum
					}
					let _this = this;
					uni.showLoading({
						title: '',
						mask: true
					});
					if(this.isDirect) {
						_this.$refs.skuPopup.close()
						let params = {sku: this.chooseSku, 
										product: {name: this.product.name, 
										picUrl: this.product.picUrl,
										price:this.product.price,
										salePrice: this.product.salePrice, 
										orchardId: this.product.orchardId, orchardName: this.product.orchardName}};
						if(this.currentAddress && this.currentAddress.detailAddress) {
							params.address = this.currentAddress;
						}
						uni.hideLoading();
						uni.navigateTo({url: '/pages/common/create-order?order=' + JSON.stringify(params)});
					}
					else {
						$H.post('/trade/cart/add', data).then(res => {
							if(res) {	
								_this.$refs.skuPopup.close()
								if(_this.isDirect) {
									$H.get('/trade/cart/getCartItem', {id: res}).then(resp => {
										if(resp) {
											let items = [];
											resp.forEach(item => {
												item.list.forEach(c => {
													items.push(c);
												})											
											})
											uni.hideLoading();
											uni.navigateTo({url: '/pages/common/payment?items=' + JSON.stringify(items)});
										}
									})
								}
								else {
									uni.hideLoading();
									_this.getCartItemNum();
								}							
							}
							else {
								uni.hideLoading();
							}
						})
					}					
				}
				else {
					uni.navigateTo({url: '/pages/common/login/login?from=' + 'notTab'})				
				}				
			},
			goBuyNow() {				
				if($U.isLogin()) {
					this.isDirect = true;
					this.cartBtnLabel = '立即下单',
					this.selectSku(this.skuList[0]);
					this.$refs.skuPopup.open('bottom')
				}
				else {
					uni.navigateTo({url: '/pages/common/login/login?from=' + 'notTab'})
				}
			},
			goCartList() {
				uni.switchTab({url:"/pages/tabbar/find/find"})
			},
			getCartItemNum() {
				let _this = this;
				if($U.isLogin()) {
					$H.get('/trade/cart/get-count').then(res => {
						if(res) {							
							_this.cartTotal = res
						}
					})
				}
				
			},
			getDefaultAddress() {
			  let _this = this;
			  if($U.isLogin()) {
				  $H.get('/member/address/get-default').then(res => {
					  if(res) {
						  _this.currentAddress = res;
						  _this.userDefaultAddr = res.detailAddress;
					  }
				  })
			  }			  
			},
			upper: function(e) {
				// console.log(e)
			},
			lower: function(e) {
				// console.log(e)
			},
			scroll: function(e) {
				// console.log(e)
				this.old.scrollTop = e.detail.scrollTop
			},
			 changeIndicatorDots(e) {
				this.indicatorDots = !this.indicatorDots
			},
			changeAutoplay(e) {
				this.autoplay = !this.autoplay
			},
			intervalChange(e) {
				this.interval = e.target.value
			},
			durationChange(e) {
				this.duration = e.target.value
			}
		}
	}
</script>

<style lang="scss" scoped>
	img,
	[alt],
	img[alt]{
	  max-width: 100%;
	}
	button::after {
		border: none;
	}
	.detail-page {
		background-color: #fff;
		padding-bottom: calc(env(safe-area-inset-bottom) + 120rpx);
	}
	.detail-page /deep/  .nav {
		position: fixed;
		top: 0;
	}
	.detail-page /deep/ .other-head-mod-mian-title {
		display: none;
	}
	.detail-page /deep/ .other-head-mod {
		border-bottom: none !important;
		background-color: transparent !important;
	}
	.detail-page /deep/ .uni-swiper-dot {
		background: rgba(255, 255, 255, 0.5);
		
		&.uni-swiper-dot-active {
			background: #fff;
		}
	}
.spu-detail {
	position: relative;
	width: 100%;
	background-color: #EAEAEA;
	.detail-top {
		position: relative;
		width: 100%;
		.spu-banner {
			.uni-margin-wrap {
				height: 650rpx;
				width: 100%;
			}
			.swiper {
				height: 650rpx;
			}
			.swiper-item {
				display: block;
				height: 650rpx;
				line-height: 750rpx;
				text-align: center;
				background-color: #ff0000;
			}
		}
		.spu-title {
			height: auto;
			padding: 24rpx 0 30rpx 20rpx;
			background: #fff;
			margin-bottom: 16rpx;
			.spu-price {
				display: flex;
				height: 48rpx;
				line-height: 48rpx;
				margin-bottom: 10rpx;
				
				h2 {
					font-weight: normal;
					font-size: 38rpx;
					
					span {
						font-size: 24rpx;
					}
				}
				.sale_price {
					text-decoration: line-through;
					font-size: 12px;
					color: #666666;
				}
			}
			.spu-title-info {
				display: flex;
				justify-content: space-between;
				
				.share {
					width: 100rpx;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					cursor: pointer;
					
					.share-icon {
						display: block;
						width: 36rpx;
						height: 36rpx;
						margin: 0 auto;
						margin-bottom: 12rpx;
						
						img {
							display: block;
							width: 100%;
							height: 100%;
						}
					}
					.share-text {
						display: block;
						font-size: 20rpx;
						color: #666666;
					}
				}
			}
			.spu-name {
				width: 100%;
				height: 84rpx;
				line-height: 40rpx;
				font-weight: bold;
				font-size: 30rpx;
				color: #222222;
				padding-right: 34rpx;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
				overflow-wrap: break-word;
				word-break: break-all;
				white-space: normal;
				overflow: hidden;
				border-right: 1px solid #ccc;
			}
			.spu-desc {
				
				.subinfo {
					color: #555;
					height: 30rpx;
					line-height: 10rpx;
					font-size: 28rpx;
					margin-top: 10rpx;
				}
			}
			
		}
		.sku-box {
			width: 100%;
			height: auto;
			background-color: #FFF;
			
			.uni-list-item {
				height: 72rpx;
				
				/deep/ .slot-box {
					font-size: 28rpx;
				}
				/deep/ .slot-box:not(.slot-text) {
					color: #666666;					
				}
			}
		}
	}
	.spu-info {
		width: 100%;
		margin-top: 16rpx;
		background-color: #FFF;
		.info-title {}
		.info-detail {
			width: 100%;
			background-color: #fff;
			.spu-images {
				display: block;
				width: 100%;	
				margin: 0;
				padding: 0;
				background-color: #fff;
				/deep/ img {
					display: block;
					width: 100%;	
					padding-left: 15rpx;
					padding-right: 15rpx;
				}
			}
			
		}
	}
	
}
/deep/ .slot-text {
	margin-left: 52rpx;
}
.sku-choose-block {
	position: relative;
	top: 20rpx;
	height: 820rpx;
	min-height: 760rpx;
	.sku-choose-btn {
		position: fixed;
		bottom: 40rpx;		    
		width: 100%;
		height: 50px;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 0 10px;
		margin: 10px 0;
		box-sizing: border-box;
		.choose-btn {
			width: 100%;
			color: #fff;
			border-radius: 200px;
			background: #FD5052;
		}
	}
}
.sku-choose-box {
	width: 100%;
	height: auto;
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	.sku-info {
		position: relative;
		width: 100%;
		border-radius: 20rpx 20rpx 0 0;
		/deep/ .uni-section {
			background-color: transparent;
		}
		/deep/ .uni-section-header {
			display: none;
		}
		/deep/ .uni-section-content {
			display: flex;
			align-items: center;
		}
		.sku-icon {
			position: relative;
			width: 30%;
			display: block;
		}
		.choose-sku {
			position: relative;
			.sku-price {
				width: 100%;
			}
			.sku-name {
				width: 100%;
				margin-top: 15rpx;
			}
		}
	}
	.sku-list {
		position: relative;
		width: 100%;
		/deep/ .uni-section-content {
			overflow: hidden;
		}
		.sku-list-item {
			position: relative;
			width: auto;
			height: 70rpx;
			float: left;
			margin: 0;
			padding-left: 10rpx;
			padding-right: 10rpx;
			padding-top: 6rpx;			
			/deep/ .uni-tag {
				color: #222222;
				border-radius: 31rpx 31rpx 31rpx 31rpx;
			}
		}
	}
	.sku-buy-num {
		position: relative;
		width: 100%;
		height: 80rpx;
		line-height: 40rpx;
		/deep/ .uni-section-content {
			display: none;
		}
	}
}

.detail-bottom {
	height: 110rpx;
	width: 100%;
	position: fixed;
	bottom: env(safe-area-inset-bottom);
	left: 0;
	background: #fff;
	border-top: 1px solid #F4F4F4;
	padding: 0 30rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	box-sizing: border-box;
	
	.detail-bottom__left {
		width: 140px;
		flex: 0 0 140px;
		display: flex;
		align-items: center;
		justify-content: center;
		
		.news,.cart {
			width: 50%;
			flex: 1;
		}
	}
	
	.detail-bottom__right {
		flex: 1;
		display: flex;
		justify-content: space-between;
	}
	
	.flex {
		display: flex;
		flex-direction: column;
		
		.icon {
			width: 36rpx;
			height: 36rpx;
			position: relative;
			margin: 0 auto;
			
			.info-num {
				position: absolute;
				top: -6rpx;
				left: calc(100% - 5px);
				background: #FD5052;
				border-radius: 200PX;
				font-size: 22rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				color: #fff;
				height: 30rpx;
				min-width: 30rpx;
				padding: 0 4px;
			}
			
			img {
				display: block;
				width: 100%;
			}
		}
		.title {
			display: block;
			font-size: 24rpx;
			height: 36rpx;
			color: #222222;
			text-align: center;
			white-space: nowrap;
		}
	}
	.news,.cart {
		// padding: 0 20rpx;
	}
	.addtocart,.placeorder {
		height: 74rpx;
		justify-content: center;
		align-items: center;
		background: #FCBC23;
		padding: 0 40rpx;
		border-radius: 200PX;
		font-size: 28rpx;
		color: #fff;
		white-space: nowrap;
	}
	.placeorder {
		background: #FD5052;
	}
}
.address_list {
	width: 100%;
	min-height: 100rpx;
	max-height: 400rpx;
	overflow: scroll;
}
</style>
